<template>
	<view class="container">
		<!-- 中心 -->
		<view class="div1">
			<view style="width: 100%;height: 1%;"></view>
			<view  class="div4">
				<view class="div5">
					<view style="width: 2%;height: 100%;float: left;"></view>
					<view style="width: 10%;height: 100%;float: left;">
						<view style="width: 100%;height: 8%;"></view>
						<u-icon name="calendar" size="35" color="black"></u-icon>
					</view>
					<view style="width: 50%;height: 100%;float: left;">
						<view style="width: 100%;height: 23%;"></view>
						<span style="font-size: 18px;font-weight: 400;margin-left: 5px;">{{ option.seriesName }}</span>
					</view>
				</view>
				<view class="card">
					<view class="card-content">
						<view class="image-container" v-for="coach in MemberuserDate" :key="coach.coachId">
							<image class="imagg"
								:src="'http://101.43.223.224:8765/image/getImageById?id=' + coach.memberUserPhoto"></image>
						</view>
						<view class="details">
							<view class="details-row">
								<view class="label"><uni-icons type="person"
										size="25"></uni-icons>教练名称：{{option.coachName}}</view>
							</view>
							<view class="details-row" v-for="coach in MemberuserDate" :key="coach.coachId">
								<view class="label"><uni-icons type="phone" size="25"></uni-icons>学员名称：{{coach.memberUserRealName}}
								</view>
							</view>
							<view class="details-row">
								<view class="label"><uni-icons type="calendar" size="25"></uni-icons>课程系列：{{option.planName}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="width: 100%;height: 2%;">
				
			</view>
			
			<view
				style="width: 90%;margin: 0 auto;display: flex;align-items: center;margin-bottom: 20rpx;justify-content: center;">
				<u-icon name="calendar" size="60rpx" color="#000000"></u-icon>
				<text style="font-size: 32rpx;">选择日期</text>
			</view>
			<view style="width: 100%;">
				<view style="width: 100%;height: 80vw;display: flex;justify-content: center;">
					<view class="" style="border-radius: 2px;background: #FFFFFF;box-shadow: 0px 2px 16px rgba(0,0,0,0.1);width: 85vw;height: 80vw;">
						<!-- 直接使用引入的组件 -->
						<zeng-calen :actDay="actDay" :chooseDay="chooseDay" @onDayClick='onDayClick' style="width: 100%;height: 100%;"></zeng-calen>
					</view>
				</view>
			</view>
			<view style="width: 100%; height: 4%;"></view>
			<view
				style="width: 90%;margin: 0 auto;display: flex;align-items: center;margin-bottom: 20rpx;margin-top: 40rpx;justify-content: center;">
				<!-- justify-content: center; -->
				<u-icon name="clock" size="50rpx" color="#000000"></u-icon>
				<text style="font-size: 32rpx;">选择时间</text>
			</view>
			<view style="width: 100%;overflow: inherit;">
				<view style="overflow: inherit;width: 100%; height: 20%; text-align: center;" >
				  <view v-for="(item, index) in morning" :key="index" class="yuyue" style="margin-bottom: 10px;border-radius: 15px;height: 9vh;" :class="{ 'time-bottom-selected': timeSelected(item.trainingTime) }">
				    <span style="font-weight: 600;" @click="selectTime(item)"> {{ item.trainingTime }} </span>
				    <br />
				    <span v-if="item.courseId>0" style="font-size: 15px; color: red;">约满</span>
				  </view>
				</view>
				<view style="width: 100%;height: 5%;text-align: center;margin-top: 23rpx;">
					<span>预约时间：{{ latestSelectedDate }} {{ selectedTime }}</span>
				</view>
				<view style="width: 60%;height: 6vh;margin: 0 auto;background: #6EE7F0;border-radius: 8px;text-align: center;margin-top: 10rpx;">
					<span style="color: rgba(250, 250, 250, 1);font-size: 24px;font-weight: 500;line-height: 6vh;" @click="handleAppointmentRequest">申请预约</span>
				</view>
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	// import uCalendar from '@/components/uCalendar/uCalendar.vue'
	export default {
		data() {
			return {
				MemberuserDate: [],
				selectedTimeId:0,
				// timeId:0,
				courseId: 0,
				id: 0,
				Id: 0,
				option: {},
				value: '',
				type: 'text',
				border: true,
				activeIndex: 0,
				yuyueActive: false,
				show: true,
				mode: 'single',
				// show1: true,
				// mode1: 'date'
				actDay: null, //用户选择的日期
				chooseDay: [], //已被投标的数据
				selectedDate: null, // 保存当前选中的日期
				selectedTime: '', // 选定的时间
				morning: [],
				afternoon: [],
			}
		},
		onLoad(options) {
			this.option = JSON.parse(options.row);
			console.log(JSON.parse(options.row))
		},
		computed: {
		    latestSelectedDate() {
		      const today = new Date().toLocaleDateString();
		      return this.actDay || today;
		    },
		},
		created() {
			this.Memberuserload();
			this.morningload();
			this.afternoonload();
		},
		methods: {
			Memberuserload() {
			    // 发起查询请求
			    uni.request({
			        url: 'http://127.0.0.1:17000/memberUser/selectMemberHeadPortrait',
			        method: "GET",
			        data: {
						userId: uni.getStorageSync('userInfo').id
			    	},
			        success: (res) => {
			            if (res.statusCode === 200) {
			                // 将查询结果中的多个任务数据存储到 Coacharray 数组
			                this.MemberuserDate = res.data.data;
			            } else {
			                // 处理请求失败的情况
			                uni.showToast({
			                    title: "请求失败",
			                    icon: "none"
			                });
			            }
			        },
			        fail: (error) => {
			            // 处理请求失败的情况
			            console.log(error)
			            uni.showToast({
			                title: "请求失败",
			                icon: "none"
			            });
			        }
			    });
			},
			// 课程状态
			getStatusText(reservationStatus) {
			  reservationStatus = parseInt(reservationStatus); // 将status转换为整数
			
			  switch (reservationStatus) {
			    case 0:
			      return '可约';
			    case 1:
			      return '爆满';
			    case 2:
			      return '爆满';
			    default:
			      return '未知状态';
			  }
			},
			timeSelected(trainingTime) {
				console.log("================",trainingTime)
				return (trainingTime === this.selectedTime)
			},
			// 处理时间选择事件
			selectTime(item) {
				// 检查所选时间是否已经约满
				if (item.courseId > 0) {
				    // 时间已经约满，显示提示消息并阻止选择
				    uni.showToast({
				        title: '该时间段已约满，请选择其他时间。',
				        icon: 'none', // 可根据需要更改图标
				    });
				    return;
				}
				// 时间可用，继续处理选择
			    this.selectedTime = item.trainingTime;
				this.timeId=item.id
				console.log(item.id)
			},
			handleAppointmentRequest() {
			  // 检查selectedTime是否为空
			  if (this.selectedTime === '') {
			    // 显示一个提示或执行其他操作
			    wx.showToast({
			      title: '请选择日期和时间',
			      icon: 'none',
			    });
			  } else {
			    // 弹出确认提示框
			    wx.showModal({
			      title: '确认预约',
			      content: '您确定要预约吗？',
			      success: (res) => {
			        if (res.confirm) {
			          // 用户点击了确定按钮，执行保存操作
			          this.save();
			        } else if (res.cancel) {
			          // 用户点击了取消按钮，可以根据需要执行其他操作
			          console.log('用户取消了预约');
			        }
			      },
			    });
			  }
			},
			async save() {
				const formattedDate = this.formatDate()
				uni.request({
					url: 'http://127.0.0.1:17000/vipPlan/reservationPlan',
					method: 'POST',
					dataType: 'json',
					data: {
						coachId: uni.getStorageSync('coach'),
						courseId: this.option.courseId,
						studentId: uni.getStorageSync('userInfo').id,
						reservationTime:formattedDate,
						courseTime:this.timeId
					}, // 需要上传的数据
					success: (res) => {
						if (res.statusCode === 200) {
							// 请求成功，保存成功
							uni.showToast({
								title: '申请成功',
								icon: 'success',
								duration: 2000,
								success: () => {
									// 在成功提示后返回上一页
									uni.navigateBack({
									  delta: 1, // 返回的页面数，1表示返回上一页
									});
								},
							});
						} else {
							// 请求成功，但保存失败
							uni.showToast({
								title: '申请失败',
								icon: 'none',
								duration: 2000,
							});
						}
					},
					fail: (error) => {
						// 请求失败
						console.error('请求失败', error);
						uni.showToast({
							title: '提交失败',
							icon: 'none',
							duration: 2000,
						});
					},
				});
			},
			formatDate() {
			  const date = new Date(this.latestSelectedDate);
			  const year = date.getFullYear();
			  const month = date.getMonth() + 1;
			  const day = date.getDate();
			  const formattedDate = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
			  return formattedDate;
			},
			morningload() {
				    // 发起查询请求
				   //  uni.request({
				   //      url: 'http://127.0.0.1:17000/trainingTime/morning',
				   //      method: "GET",
				   //      data: {
							
				   //  	},
				   //      success: (res) => {
				   //          if (res.statusCode === 200) {
				   //              // 将查询结果中的多个任务数据存储到 morning 数组
				   //              this.morning = res.data.data;
				   //          } else {
				   //              // 处理请求失败的情况
				   //              uni.showToast({
				   //                  title: "请求失败",
				   //                  icon: "none"
				   //              });
				   //          }
				   //      },
				   //      fail: (error) => {
				   //          // 处理请求失败的情况
				   //          console.log(error)
				   //          uni.showToast({
				   //              title: "请求失败",
				   //              icon: "none"
				   //          });
				   //      }
				   //  });
					
					const formattedDate = this.formatDate();
					var ths = this;
					uni.request({
						url: 'http://127.0.0.1:17000/vipPlan/selectReservationTime',
						method: 'GET',
						data: {
							coachId: uni.getStorageSync("coach"),
							reservationTime:formattedDate
						},
						// userInfo:res.
						success: function(res) {
							if(res.data.code==200){
								ths.morning = res.data.data;
							}else {
								ths.morning = []
							}
							
							
						},
						fail: function(error) {
							// 处理请求失败
							console.error('角色查询失败,请检查网络');
						}
					})
			},
			afternoonload() {
				    // 发起查询请求
				    uni.request({
				        url: 'http://127.0.0.1:17000/trainingTime/afternoon',
				        method: "GET",
				        data: {
							
				    	},
				        success: (res) => {
				            if (res.statusCode === 200) {
				                // 将查询结果中的多个任务数据存储到 afternoon 数组
				                this.afternoon = res.data.data;
				            } else {
				                // 处理请求失败的情况
				                uni.showToast({
				                    title: "请求失败",
				                    icon: "none"
				                });
				            }
				        },
				        fail: (error) => {
				            // 处理请求失败的情况
				            console.log(error)
				            uni.showToast({
				                title: "请求失败",
				                icon: "none"
				            });
				        }
				    });
			},
			// formatDate(date) {
			//     if (!date) return '';
			//     const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
			//     return new Date(date).toLocaleDateString('zh-CN', options);
			// },
			calculateTimeDifference(startTime, endTime) {
			    // 确保 startTime 和 endTime 是有效的 JavaScript 日期对象或时间戳
			    startTime = new Date(startTime);
			    endTime = new Date(endTime);
			    				
			    // 计算时间差（分钟）
			    const timeDiffInMinutes = Math.floor((endTime - startTime) / (60 * 1000));
			    				
			    if (timeDiffInMinutes >= 60) {
			        // 超过一小时，计算小时和剩余分钟
			        const hours = Math.floor(timeDiffInMinutes / 60);
			        const remainingMinutes = timeDiffInMinutes % 60;
			    				
			        if (remainingMinutes > 0) {
			            return hours + " 小时 " + remainingMinutes + " 分";
			        } else {
			            return hours + " 小时";
			        }
			    } else {
			        // 不足一小时，直接以分钟为单位显示
			        return timeDiffInMinutes + " 分钟";
			    }
			},
			click(event) {
				console.log('index', event.index);
				this.activeIndex = event.index;
			},

			showCal() {
				console.log(111)
				this.show1 = true
			},

			// 展开日历
			onDayClick(data) {
			  const choose = new Date(data.date); // 将点击的日期转换为 Date 对象
			
			  // 如果 startTime 和 endTime 不是 Date 对象，将它们转换为 Date 对象
			  const startTime = new Date(this.option.startTime);
			  const endTime = new Date(this.option.endTime);
			
			  // 获取今天的日期，格式与 choose 相同
			  const today = new Date().toLocaleDateString();
			
			  // 如果用户点击的日期已经存在
			  if (this.actDay && choose.getTime() === new Date(this.actDay).getTime()) {
			    this.actDay = null;
			    this.selectedDate = null;
			  } else if (this.chooseDay.includes(choose.toLocaleDateString())) {
			    uni.showToast({
			      title: '这个日期已经被选中了',
			      icon: 'none',
			    });
			  } else if (choose < startTime || choose > endTime || choose < new Date(today)) {
			    uni.showToast({
			      title: '请选择今天日期之后的日期',
			      icon: 'none',
			    });
			  } else {
			    this.actDay = choose.toLocaleDateString(); // 将选中的日期保存为字符串
			    this.selectedDate = choose;
			  }
			},
		}
	}
</script>

<style scoped>
	.zeng-calen-day.selected {
	  position: relative;
	  border-radius: 50%;
	}
	
	.zeng-calen-day.selected:after {
	  content: '';
	  position: absolute;
	  bottom: 0;
	  left: 50%;
	  transform: translateX(-50%);
	  width: 6px !important;
	  height: 6px !important;
	  background-color: #000 !important;
	  border-radius: 50% !important;
	}
	/* 设置背景图片 */
	.container {
		/* display: flex; */
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-image: url('http://101.43.223.224:8765/image/getImageById?id=6755');
		overflow: inherit;
	}

	/* 在父容器上添加样式 */
	.parent-container {
	  white-space: nowrap;
	}
	.yuyue {
	  width: 29%;
	  height: 90%;
	  text-align: center;
	  display: inline-flex; /* 使用 Flex 布局 */
	  flex-direction: column; /* 纵向排列 */
	  align-items: center; /* 垂直居中 */
	  justify-content: center; /* 水平居中 */
	  box-shadow: 1px 0px 8px rgba(0, 0, 0, 0.25);
	  background: white;
	  transition: background-color 0.3s ease;
	  margin-right: 15px; /* 设置右侧间距 */
	}
	
	.yuyue.active {
	  /* background: rgba(158, 207, 255, 0.5); */
	}

	.div6{
		width: 96%;
		height: 70%;
		border-radius: 9px;
		background-color: #F7F7F7;
		margin: 0 auto;
	}
	.div5{
		width: 100%;
		height: 25%;
		/* background-color: yellow; */
	}
	.div4{
		/* width: 100%; */
		height: 21vh;
		/* border-radius: 6px;box-shadow: 0px 2px 10px #dfdfdf; */
		/* border: 0.3px solid ##d4c8c8; */
		/* background-color: pink; */
	}

	.div1 {
		width: 100%;
		height: 100%;
		/* background: rgba(255, 255, 255, 1); */
		border-radius: 100px 100px, 0px, 0px;
		border-top-left-radius: 40px;
		border-top-right-radius: 40px;
	}

	.img1 {
		width: 100%;
		height: 100%;
	}
	
	.card {
		width: 90vw;
		height: 126px;
		border-radius: 25rpx 25rpx 25rpx 25rpx;
		background-color: rgba(255, 255, 255, 0.5);
		/* background-color: #fff; */
		margin: 0 auto;
		padding: 20rpx;
		box-sizing: border-box;
		box-shadow: 0 2px 10px #dfdfdf;
		margin-bottom: 24px;
		
	}
	
	.card-header {
		height: 50rpx;
	}
	
	.details {
		font-size: 26rpx;
		float: left;
		color: #5C5C5C;
	}
	
	.details-row {
		height: 30rpx;
		margin-top: 20rpx;
	}
	.image-container {
		width: 160rpx;
		height: 160rpx;
		float: left;
	}
	
	.imagg {
		width: 140rpx;
		height: 140rpx;
		border-radius: 4px;
		margin-top: 20rpx;
		border-radius: 50%;
	}
	.label {
		float: left;
	}
	
	.label-top {
		float: left;
		font-size: 36rpx;
		color: black;
		margin-bottom: 10rpx;
	}
	.time-bottom-selected {
		/* width: 31%;
		height: 60px;
		float: left;
		margin: 1%;
		box-sizing: border-box;
		padding: 8px; */
		background-color: #C7FBFF;
		/* color: black;
		box-shadow: 0 2px 10px #dfdfdf;
		border-radius: 15rpx 15rpx 15rpx 15rpx; */
	}
	
	.time-bottom-selected .keyue {
		color: #000;
	}
</style>